package com.jwdf.uda.ui.fragment.user.personal;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.databinding.FragmentAccountSecurityBinding;
import com.jwdf.uda.event.IndividualEvent;
import com.jwdf.uda.event.ThirdPartEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.ForgotPasswordStep1Action;
import com.jwdf.uda.http.action.UnbindQQAccountAction;
import com.jwdf.uda.http.action.UnbindWechatAccountAction;
import com.jwdf.uda.http.action.UnbindWeiboAccountAction;
import com.jwdf.uda.http.action.UserInfoAction;
import com.jwdf.uda.ui.activity.ChangeUserNameActivity;
import com.jwdf.uda.ui.activity.ForgetPasswordActivity;
import com.jwdf.uda.ui.activity.UserBindMobileActivity;
import com.jwdf.uda.ui.activity.UserLoginPassActivity;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.ToastUtils;
import com.jwdf.uda.utils.UdaUtils;
import com.jwdf.uda.view.dialog.ChoiceDialog;
import com.jwdf.uda.view.dialog.ConfirmDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/9/20.
 */
public class AccountSecurityFragment extends BaseFragment {
    private final static int CODE_OLD_PASS = 1;
    private final static int CODE_MOBILE = 2;
    private final static int CODE_TITLE = 3;
    private static final int MSG_AUTH_COMPLETE = 1;
    private static final int MSG_AUTH_CANCEL = 2;
    private static final int MSG_AUTH_ERROR = 3;
    private FragmentAccountSecurityBinding mDataBinding;
    private ChoiceDialog mChoiceDialog;
    private ConfirmDialog mWechatDialog;
    private ConfirmDialog mWeiboDialog;
    private ConfirmDialog mQqDialog;
    private  PbBean.PbUserInfo userInfo;
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what) {
                case MSG_AUTH_COMPLETE:
                    Bundle data = msg.getData();
                    String type = data.getString("type");
                    String openId = data.getString("openId");
                    String name = data.getString("name");
                    String pic = data.getString("pic");
                    ThirdPartEvent event = new ThirdPartEvent(ThirdPartEvent.EVENT_AUTH_COMPLETE);
                    event.loginType = type;
                    event.usrOpenId = openId;
                    event.usrName = name;
                    event.usrPic = pic;
                    EventBusUtil.post(event);
                    break;
                case MSG_AUTH_CANCEL:
                    closeProgressDialog();
                    break;
                case MSG_AUTH_ERROR:
                    closeProgressDialog();
                    Bundle data2 = msg.getData();
                    ToastUtils.show(getContext(), data2.getString("content"));
                    break;
            }
        }
    };
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mDataBinding = FragmentAccountSecurityBinding.inflate(inflater, container, false);
        initViews();
        return mDataBinding.getRoot();
    }

//    @Override
//    public void onResume() {
//        super.onResume();
//        closeProgressDialog();
//    }
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mDataBinding.setAccountSecurityFragment(this);
}
    private void initViews() {
        requestUserInfo();
//        userInfo = (PbBean.PbUserInfo) getArguments().getSerializable("user_info");
//        loadUserInfo(userInfo);
    }
    private void loadUserInfo(PbBean.PbUserInfo userInfo) {
        this.userInfo=userInfo;
        mDataBinding.tvMobile.setText(TextUtils.isEmpty(userInfo.getMobile()) ? getString(R.string.account_none_bind) : UdaUtils.hiddenPhoneNumber(userInfo.getMobile()));
        if (!TextUtils.isEmpty(userInfo.getMobile())) {
            mDataBinding.rlMobile.setTag(R.id.tag_mobile, userInfo.getMobile());
        }
        mDataBinding.rlWechat.setTag(R.id.tag_wechat, userInfo.getWechatAccount());
        mDataBinding.rlWeibo.setTag(R.id.tag_weibo, userInfo.getWeiboAccount());
        mDataBinding.rlQq.setTag(R.id.tag_qq,userInfo.getQqAccount());
        mDataBinding.tvWechat.setText(TextUtils.isEmpty(userInfo.getWechatAccount()) ? getString(R.string.account_none_bind) : getString(R.string.account_binded));
        mDataBinding.tvWeibo.setText(TextUtils.isEmpty(userInfo.getWeiboAccount()) ? getString(R.string.account_none_bind) : getString(R.string.account_binded));
        mDataBinding.tvQq.setText(TextUtils.isEmpty(userInfo.getQqAccount())? getString(R.string.account_none_bind) : getString(R.string.account_binded));
        mDataBinding.tvPasswd.setText(userInfo.getIsVisitor() ? getString(R.string.passwd_setting) : getString(R.string.passwd_modify));
    }
    public void onUserMobileClick(View view) {
        RelativeLayout tv = (RelativeLayout) view;
        String mobile = mDataBinding.tvMobile.getText().toString();
        if (TextUtils.equals(getString(R.string.account_none_bind), mobile)) {
            UserBindMobileActivity.start(view.getContext(), getString(R.string.bind_mobile), "");
        } else {
            UserBindMobileActivity.start(view.getContext(), getString(R.string.bind_mobile), (String) tv.getTag(R.id.tag_mobile));
        }
    }
    public void onUserWechatClick(View view) {
        RelativeLayout wechat = (RelativeLayout) view;
        String openId = (String) wechat.getTag(R.id.tag_wechat);
        if(TextUtils.isEmpty(openId)) {
            thirdPartyLogin(Wechat.NAME);
        } else {
            showWechatConfirmDialog(openId);
        }
    }



    private void showWechatConfirmDialog(final String openId){
        if (mWechatDialog == null) {
            mWechatDialog = new ConfirmDialog(getContext(), getString(R.string.dialog_message_wechat), getString(R.string.dialog_cancel), getString(R.string.dialog_unbind_sure), new ConfirmDialog.CallbackListener() {
                @Override
                public void clickNo() {

                }

                @Override
                public void clickYes() {
                    unBindWechatAccount(openId);
                }
            });
        }
        mWechatDialog.show();
    }
    private void unBindWechatAccount(String openId) {
        onNewRequestCall(UnbindWechatAccountAction.newInstance(getContext(), openId).request(new AHttpService.IResCallback<PbBean.PbResUserUnbindWeChatAccount>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserUnbindWeChatAccount> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                    return;
                }
                requestUserInfo();
            }
        }));
    }
    private void requestUserInfo() {
        onNewRequestCall(UserInfoAction.newInstance(getContext()).request(new AHttpService.IResCallback<PbBean.PbResUserGetInfo>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserGetInfo> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (getView() != null) {
                    if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_operation))) {
                        return;
                    }
                    PbBean.PbResUserGetInfo body = response.body();
                    if (body != null) {
                        PbBean.PbUserInfo userInfo = body.getUserInfo();
                        loadUserInfo(userInfo);
                    }
                }
            }
        }));
    }
    private void thirdPartyLogin(final String typeName) {
        showProgressDialog();
        Platform platform = ShareSDK.getPlatform(getContext(), typeName);
        if (platform.isAuthValid()) {
            platform.removeAccount(true);
        }
        platform.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Message msg = new Message();
                msg.what = MSG_AUTH_COMPLETE;
                Bundle bundle = new Bundle();
                bundle.putString("type", typeName);
                bundle.putString("openId", platform.getDb().getUserId());
                bundle.putString("name", platform.getDb().getUserName());
                bundle.putString("pic", platform.getDb().getUserIcon());
                msg.setData(bundle);
                mHandler.sendMessage(msg);
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Message msg = new Message();
                msg.what = MSG_AUTH_ERROR;
                Bundle bundle = new Bundle();
                if(typeName.equals(Wechat.NAME)){
                    bundle.putString("content", "请确认手机已经安装最新版本微信客户端");
                }else if(typeName.equals(SinaWeibo.NAME)){
                    bundle.putString("content","新浪微博登录失败");
                }else {
                    bundle.putString("content","QQ登录失败");
                }
                msg.setData(bundle);
                mHandler.sendMessage(msg);
            }

            @Override
            public void onCancel(Platform platform, int i) {
                mHandler.sendEmptyMessage(MSG_AUTH_CANCEL);
            }
        });
        if(typeName.equals(QQ.NAME)){
            platform.SSOSetting(false);
        }else {
            platform.SSOSetting(true);
        }
        platform.showUser(null);
    }
    public void onUserWeiboClick(View view) {
        RelativeLayout weibo = (RelativeLayout) view;
        String openId = (String) weibo.getTag(R.id.tag_weibo);
        if(TextUtils.isEmpty(openId)) {
            thirdPartyLogin(SinaWeibo.NAME);
        } else {
            showWeiboConfirmDialog(openId);
        }
    }
    private void showWeiboConfirmDialog(final String openId) {
        if(mWeiboDialog == null) {
            mWeiboDialog = new ConfirmDialog(getContext(), getString(R.string.dialog_message_weibo), getString(R.string.dialog_cancel), getString(R.string.dialog_unbind_sure),
                                                    new ConfirmDialog.CallbackListener() {
                @Override
                public void clickNo() {

                }

                @Override
                public void clickYes() {
                    unBindWeiboAccount(openId);
                }
            });
        }
        mWeiboDialog.show();
    }
    private void unBindWeiboAccount(String openId) {
        onNewRequestCall(UnbindWeiboAccountAction.newInstance(getContext(), openId).request(new AHttpService.IResCallback<PbBean.PbResUserUnbindWeiboAccount>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserUnbindWeiboAccount> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if(HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                    return;
                }
                requestUserInfo();
            }
        }));
    }

    public void onUserQQClick(View view) {
        RelativeLayout qq =(RelativeLayout) view;
        String openId =(String) qq.getTag(R.id.tag_qq);
        if(TextUtils.isEmpty(openId)){
            thirdPartyLogin(QQ.NAME);
        }else {
            showQQConfirmDialog(openId);
        }
    }
    private void showQQConfirmDialog(final String openId) {
        if(mQqDialog == null) {
            mQqDialog = new ConfirmDialog(getContext(), getString(R.string.dialog_message_qq), getString(R.string.dialog_cancel), getString(R.string.dialog_unbind_sure),
                    new ConfirmDialog.CallbackListener() {
                        @Override
                        public void clickNo() {

                        }

                        @Override
                        public void clickYes() {
                            unBindQQAccount(openId);
                        }
                    });
        }
        mQqDialog.show();
    }
    private void unBindQQAccount(String openId) {
        onNewRequestCall(UnbindQQAccountAction.newInstance(getContext(), openId).request(new AHttpService.IResCallback<PbBean.PbResUserUnbindQqAccount>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserUnbindQqAccount> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if(HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                    return;
                }
                requestUserInfo();
            }
        }));
    }

    public void onUseSetPassClick(View view) {
        String action = mDataBinding.tvPasswd.getText().toString();
        if(TextUtils.equals(action, getString(R.string.passwd_setting))) {
            ChangeUserNameActivity.start(view.getContext(), getString(R.string.account_set_passwd));
        } else {
            showChoiceDialog();
        }
    }
    private void showChoiceDialog() {
        mChoiceDialog = new ChoiceDialog(getActivity());
        mChoiceDialog.setShowHeader(true);
        List<ChoiceDialog.ChoiceItem> items = new ArrayList<>();
//        items.add(new ChoiceDialog.ChoiceItem(CODE_TITLE, getString(R.string.dialog_modify), R.color.acc8));
        items.add(new ChoiceDialog.ChoiceItem(CODE_OLD_PASS, getString(R.string.dialog_choice_old_pass), R.color.acc3));
        items.add(new ChoiceDialog.ChoiceItem(CODE_MOBILE, getString(R.string.dialog_choice_mobile), R.color.acc3));
        mChoiceDialog.setChoiceItems(items);
        mChoiceDialog.setCallbackListener(new ChoiceDialog.CallbackListener() {
            @Override
            public void onItemClick(ChoiceDialog.ChoiceItem item) {
                switch(item.getCode()) {
                    case CODE_OLD_PASS:
                        UserLoginPassActivity.start(getContext(), CODE_OLD_PASS);
                        break;
                    case CODE_MOBILE:
                        if(!TextUtils.isEmpty(userInfo.getMobile())) {
                            authMobieCode(userInfo.getMobile());
                        } else {
                            Toast.makeText(getContext(), "您还未绑定手机", Toast.LENGTH_LONG).show();
                        }
                        break;
                }
            }
        });
        mChoiceDialog.show();
    }
    private void authMobieCode(final String mobile) {
        onNewRequestCall(ForgotPasswordStep1Action.newInstance(getContext(), mobile).request(new AHttpService.IResCallback<PbBean.PbResUserForgotPasswordStep1>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserForgotPasswordStep1> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if(getView() != null) {
                    if(HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                        return;
                    }
                    ForgetPasswordActivity.start(getContext(), "修改密码", userInfo.getMobile());
                    //                    UserEvent event = new UserEvent();
                    //                    event.setEvent(UserEvent.EVENT_STEP_1);
                    //                    event.setExtra(mobile);
                    //                    EventBusUtil.post(event);
                }
            }
        }));
    }
    public void onSavaUserInfo(View view) {
        EventBusUtil.post(new IndividualEvent(IndividualEvent.USER_SAVE_INFO_EVENT));
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBusUtil.registerEvent(this);
    }
    @Override
    public void onDestroy() {
        EventBusUtil.unregisterEvent(this);
        super.onDestroy();
    }
    public void onEvent(IndividualEvent event) {
        if(event.userInfo != null) {
            loadUserInfo(event.userInfo);
        } else {
            if(IndividualEvent.USER_WEIBO_EVENT == event.getEvent() || IndividualEvent.USER_WECHAT_EVENT == event.getEvent()) {
                closeProgressDialog();
            }
            requestUserInfo();
        }
    }
    public void onEvent(ThirdPartEvent event) {
        if(ThirdPartEvent.EVENT_CLOSE_PROGRESS == event.getEvent()) {
            closeProgressDialog();
        }
    }
}
